<?php
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 后台欢迎页
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\common\controller\Adminbase;
use app\Constant\OrderConstant;
use app\model\Order;
use app\model\User;
use app\service\AgentService;
use libs\Redis;
use think\App;
use think\Db;

class AdminData extends Adminbase
{
    public function index()
    {
        $type = $this->request->param('type');
        switch ($type) {
            case '2': //本周
                $time = 'week';
                break;
            case '3': //本月
                $time = 'month';
                break;
            case '4': //本年
                $time = 'year';
                break;
            default:
                $time = 'today';
        }
        $order            = Order::field('id, total, actual_commission')
            ->whereIn('commission_status', [20, 100])
            ->whereTime('create_time', $time)->select()->toArray();
        $order_count      = count($order);
        $order_total      = array_sum(array_column($order, 'total'));
        $order_commission = array_sum(array_column($order, 'actual_commission'));
        $tk_add           = User::where('status', 1)
            ->whereTime('create_time', $time)
            ->where('bind_status', 1)
            ->count();

        $users    = User::field('id, nickname, bind_status')->where('status', 1)->select()->toArray();
        $tk_users = 0;
        foreach ($users as $user) {
            if ($user['bind_status'] == 1) {
                $tk_users++;
            }
        }
        return json([
            'code' => 0,
            'data' => [
                'users'      => count($users),
                'tk_add'     => $tk_add,
                'tk_users'   => $tk_users,
                'orders'     => $order_count,
                'total'      => $order_total > 0 ? number_format($order_total / 100, 2) : "0.00",
                'commission' => $order_commission > 0 ? number_format($order_commission / 100, 2) : "0.00",
            ],
        ]);
    }

    public function ranking_data()
    {
        $type      = $this->request->param('type');
        $date_type = $this->request->param('date_type');
        $date      = $this->request->param('date');
        $time      = '';
        if ($date_type) {
            switch ($date_type) {
                case '2': //本周
                    $time = 'week';
                    break;
                case '3': //本月
                    $time = 'month';
                    break;
                case '4': //本年
                    $time = 'year';
                    break;
                default:
                    $time = 'today';
            }
        }
        $list = [];
        switch ($type) {
            case 'goods':
                $query = Order::field('o.goods_id, sum(o.actual_commission) as total, g.title')
                    ->alias('o')
                    ->join('goods g', 'o.goods_id = g.id')
                    ->whereIn('o.commission_status', [20, 100]);
                if ($time) {
                    $query = $query->whereTime('o.create_time', $time);
                }
                if ($date) {
                    $date_range = explode(' 至 ', $date);
                    $start      = strtotime($date_range[0]);
                    $end        = strtotime($date_range[1] ?? $date_range[0] . ' 23:59:59');
                    $query      = $query->whereBetween('o.create_time', [$start, $end]);
                }
                $list = $query
                    ->group('o.goods_id')
                    ->withAttr('total', function ($value) {
                        return '¥' . number_format($value / 100, 2);
                    })
                    ->limit(15)
                    ->order('total', 'desc')
                    ->select()->toArray();
                break;
            case 'users':
                $query = Order::field('o.user_id, sum(o.commission) as total, u.nickname as title')
                    ->alias('o')
                    ->join('user u', 'o.user_id = u.id')
                    ->whereIn('o.commission_status', [20, 100]);
                if ($time) {
                    $query = $query->whereTime('o.create_time', $time);
                }
                if ($date) {
                    $date_range = explode(' 至 ', $date);
                    $start      = strtotime($date_range[0]);
                    $end        = strtotime($date_range[1] ?? $date_range[0] . ' 23:59:59');
                    $query      = $query->whereBetween('o.create_time', [$start, $end]);
                }
                $list = $query
                    ->group('o.user_id')
                    ->withAttr('total', function ($value) {
                        return '¥' . number_format($value / 100, 2);
                    })
                    ->limit(15)
                    ->order('total', 'desc')
                    ->select()->toArray();
                break;
            case 'invite':
                $query = User::field('id, nickname as title, invite_count as total');
                if ($time) {
                    $query = $query->whereTime('create_time', $time);
                }
                if ($date) {
                    $date_range = explode(' 至 ', $date);
                    $start      = strtotime($date_range[0]);
                    $end        = strtotime($date_range[1] ?? $date_range[0] . ' 23:59:59');
                    $query      = $query->whereBetween('create_time', [$start, $end]);
                }
                $list = $query
                    ->limit(15)
                    ->withAttr('total', function ($value) {
                        return $value . '人';
                    })
                    ->order('invite_count', 'desc')
                    ->select()->toArray();
                break;
        }
        return json([
            'code' => 0,
            'data' => $list,
        ]);
    }

    /**
     * 折线图数据
     * @return \think\response\Json
     */
    public function line()
    {
        $type       = $this->request->param('type');
        $date_range = $this->request->param('date');
        if ($date_range) {
            $date_range = explode(' 至 ', $date_range);
            $date       = $start = strtotime($date_range[0]);
            $end        = strtotime($date_range[1] . ' 23:59:59');
            do {
                $days[] = date('Y-m-d', $date);
                $date   = strtotime('+1 day', $date);
            } while ($date <= $end);
        } else {
            $recent_days = getRecentDays();
            $start       = strtotime($recent_days[0]['value']);
            $end         = strtotime($recent_days[count($recent_days) - 1]['value'] . ' 23:59:59');
            $days        = array_column($recent_days, 'value');
        }
        $data = $count = [];
        switch ($type) {
            case 'user':
                $users             = User::field('id, create_time, login_time')
                    ->withAttr('create_time', function ($value) {
                        return date('Y-m-d', $value);
                    })
                    ->withAttr('login_time', function ($value) {
                        return date('Y-m-d', $value);
                    })
                    ->where('status', 1)
                    ->where('bind_status', 1)
                    ->whereBetween('create_time', [$start, $end])->select()->toArray();
                $date_user         = $date_user_active = $count = [];
                $user_add          = $user_active = 0;
                $active_date_start = date('Y-m-d', strtotime('-3 day', $end));
                foreach ($users as $item) {
                    $user_add++;
                    if ($item['login_time'] >= $active_date_start) {
                        $user_active++;
                    }
                    $date_user[$item['create_time']][]       = $item;
                    $date_user_active[$item['login_time']][] = $item;
                }
                $count = [
                    'user_add'    => $user_add,
                    'user_active' => $user_active
                ];
                $total = $active = [];
                foreach ($days as $day) {
                    $user        = $date_user[$day] ?? [];
                    $total[]     = count($user);
                    $active_user = $date_user_active[$day] ?? [];
                    $active[]    = count($active_user);
                }
                $data = [
                    'total'  => $total,
                    'active' => $active
                ];
                break;
            case 'order':
                $orders = Order::field('id, commission_status, create_time, total, actual_commission')
                    ->withAttr('create_time', function ($value) {
                        return date('Y-m-d', $value);
                    })
                    ->whereIn('commission_status', [20, 100])
                    ->whereBetween('create_time', [$start, $end])->select()->toArray();

                $order_count      = count($orders);
                $order_total      = array_sum(array_column($orders, 'total'));
                $order_commission = array_sum(array_column($orders, 'actual_commission'));
                $count            = [
                    'total'       => $order_count,
                    'sales'       => $order_total > 0 ? number_format($order_total / 100, 2) : "0.00",
                    'commissions' => $order_commission > 0 ? number_format($order_commission / 100, 2) : "0.00",
                ];

                $date_order = [];
                foreach ($orders as $item) {
                    $date_order[$item['create_time']][] = $item;
                }
                $total = $sales = $commissions = [];
                foreach ($days as $day) {
                    $day_total = $day_sales = $day_commissions = 0;
                    $order     = $date_order[$day] ?? [];
                    if ($order) {
                        $day_total       = count($order);
                        $day_sales       = array_sum(array_column($order, 'total'));
                        $day_commissions = array_sum(array_column($order, 'actual_commission'));
                    }
                    $total[]       = $day_total;
                    $sales[]       = $day_sales / 100;
                    $commissions[] = $day_commissions / 100;
                }


                $data = [
                    'total'       => $total,
                    'sales'       => $sales,
                    'commissions' => $commissions,
                ];
                break;
        }
        return json(['code' => 0, 'data' => $data, 'xAxis' => $days, 'count' => $count]);
    }
}
